<?php

namespace backend\controllers;

use Yii;
use yii\web\Response;
use yii\web\Controller;
use yii\helpers\ArrayHelper;

/**
 * 基础 控制器
 * Class BaseController
 * @package backend\controllers
 */
abstract class BaseController extends Controller
{

    /**
     * beforeAction
     * @param \yii\base\Action $action
     * @return bool
     * @throws \yii\web\BadRequestHttpException
     */
    public function beforeAction($action)
    {
//        if (!Yii::$app->user->isGuest && $action->controller->id != 'site') {
//
//        }
        return parent::beforeAction($action);
    }

    /**
     * sessionSuccess
     * @param string $message
     */
    public function sessionSuccess($message = '操作成功')
    {
        session()->setFlash('success',$message);
    }

    /**
     * sessionError
     * @param string $message
     */
    public function sessionError($message = '操作失败')
    {
        session()->setFlash('error',$message);
    }

    /**
     * sessionWarning
     * @param string $message
     */
    public function sessionWarning($message = '警告')
    {
        session()->setFlash('warning',$message);
    }

    /**
     * sessionInfo
     * @param string $message
     */
    public function sessionInfo($message = '提示')
    {
        session()->setFlash('info',$message);
    }

    /**
     * asSuccessJson
     * @param array $data
     * @param string $message
     * @return Response
     */
    public function asSuccessJson( $data = [], $message = '操作成功')
    {
        return $this->returnResult(1,$message,$data);
    }

    /**
     * asErrorJson
     * @param string $message
     * @param array $data
     * @return Response
     */
    public function asErrorJson($message = '操作失败',$data = [])
    {
        return $this->returnResult(0,$message,$data);
    }

    /**
     * returnResult
     * @param int $code
     * @param string $message
     * @param array $data
     * @return Response
     */
    public function returnResult($code = 404, $message = '未知错误', $data = [])
    {
        return $this->asJson([
            'code' => (int)$code,
            'message' => trim($message),
            'data' => $data ? ArrayHelper::toArray($data) : [],
        ]);
    }

    /**
     * closeWindows
     * @param int $refresh
     * @return string
     */
    public function closeWindows($refresh=1)
    {
        return '<script>window.parent.$.refreshWindows('.($refresh?1:0).');</script>';
    }

}
